package com.usian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.common.constants.message.FollowBehaviorConstants;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ApAuthorFeign;
import com.usian.user.mapper.ApUserFanMapper;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.UserRelationService;
import com.usian.utils.threadlocal.UserIdThreadLocalUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class UserRelationServiceImpl extends BaseServiceImpl<ApUserFollowMapper, ApUserFollow> implements UserRelationService {


    @Autowired
    private ApAuthorFeign apAuthorFeign;

    @Autowired
    private ApUserFanMapper fanMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    @GlobalTransactional
    public ResponseResult follow(UserRelationDto dto) {

        if (dto == null) return errorParam;

        Integer userId = UserIdThreadLocalUtils.getUserId();
        if (StringUtils.isEmpty(userId)) return needLogin;
        ApUser apUser = apUserMapper.selectById(userId);
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult("文章id不存在");
        }
        ApAuthor author = apAuthorFeign.findById(dto.getAuthorId());
        if (author == null) return ResponseResult.errorResult("文章作者不存在");
        Integer followId = author.getUserId();

        //判断是要关注：0
        if (dto.getOperation() == 0) {


            if (author.getUserId() == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注人不存在");
            }

            //保存关联关系
            return saveRelation(apUser, author, dto.getArticleId());
        } else {

            return followCancelByUserId(apUser, followId);
        }
    }

    /**
     * 取消关注的处理逻辑
     *
     * @param apUser
     * @param followId
     * @return
     */
    private ResponseResult followCancelByUserId(ApUser apUser, Integer followId) {
        //先查再删
        ApUserFollow apUserFollow = getOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId()).
                eq(ApUserFollow::getFollowId, followId));
        if (apUserFollow == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "未关注");
        } else {
            ApUserFan apUserFan = fanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId).
                    eq(ApUserFan::getFansId, apUser.getId()));
            //删除用户粉丝信息
            fanMapper.delete(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, followId).eq(ApUserFan::getFansId, apUser.getId()));

            //删除用户关注信息

            remove(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId()).eq(ApUserFollow::getFollowId, followId));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    private ResponseResult saveRelation(ApUser apUser, ApAuthor author,Long articleId) {

        ApUserFan userFan = fanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, author.getUserId())
                .eq(ApUserFan::getFansId, apUser.getId()));
        if (userFan == null) {
            userFan = new ApUserFan();
            //保存登录用户关注作者关系
            ApUserFollow userFollow = new ApUserFollow();
            userFollow.setUserId(apUser.getId());
            userFollow.setFollowId(author.getUserId());
            userFollow.setFollowName(author.getName());
            userFollow.setLevel(Short.valueOf("1"));
            userFollow.setIsNotice(true);
            userFollow.setCreatedTime(new Date());
            boolean save = save(userFollow);
            //保存文章作者粉丝关系
            userFan.setUserId(author.getUserId());
            userFan.setFansId(apUser.getId().longValue());
            userFan.setFansName(apUser.getName());
            userFan.setLevel((short) 0);
            userFan.setIsDisplay(true);
            userFan.setIsShieldLetter(false);
            userFan.setIsShieldComment(false);
            userFan.setCreatedTime(new Date());
            fanMapper.insert(userFan);

            // 记录关注行为
            FollowBehaviorDto dto = new FollowBehaviorDto();
            dto.setFollowId(author.getUserId());
            dto.setArticleId(articleId);
            dto.setUserId(apUser.getId());
            //异步发送消息，保存关注行为
            kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(dto));

            return ResponseResult.okResult("关注成功");
        } else {
            return ResponseResult.errorResult("已添加粉丝关系");
        }


    }
}
